package medium;

import javax.swing.plaf.TextUI;

/**
 * 给一个字符串，求最长子串（不包含重复字符）的长度
 * <p>
 * 比如：
 * 1. abcabcbb 的最长子串 abc
 * 2. bbbbb 的最长子串 b
 * 3. pwwkew 的最长子串 wke
 *
 * @author zj
 * @date 2018/08/01
 * @see <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/description/">题目</a>
 * @see <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/">解答</a>
 */
public class LongestSubstring {

    /**
     * 设置两个参数，子字符串和最长子串
     * 遍历字符串，每次遍历，判断子字符串长度是否大于最长子串，如果是，替换该字串
     * 将当前下标字符加入子字符串中，并查询是否出现之前的子字符串中
     * 如果存在，子字符串从相同字符之后开始
     */
    private int lengthOfLongestSubstring(String s) {
        String ls = null;
        StringBuilder ss = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            String temp = s.substring(i, i + 1);
            int idx = ss.indexOf(temp);
            if (idx != -1) {
                ss.delete(0, idx + 1);
            }
            ss.append(temp);
            if (ls == null || ss.length() > ls.length()) {
                ls = ss.toString();
            }
        }
        return ls == null ? 0 : ls.length();
    }

    public static void main(String[] args) {
        LongestSubstring substring = new LongestSubstring();
        System.out.println(substring.lengthOfLongestSubstring("pwwkew"));
    }

}
